#include<stdio.h>
#include "../include/BST.h"
#include "../include/errorcodes.h"


void list_file(char *filePath, char *outputfile)
{
	int blockNumr = 0, file_offset1 = 0;
	char ch='0', readChars;
	
	FILE *fp = fopen(outputfile, "w");
	
	/*if(outputfile==NULL)
	{
		printf("%s\n", ERR_VFS_LISTFILE_04);
	}
	else if(filePath == NULL)
	{
		printf("%s\n", ERR_VFS_LISTFILE_03);
	}*/
	
	
	if(fp == NULL)
	{
		printf("listfile_FAILURE %s\n", ERR_VFS_LISTFILE_03);
		return;
	}
	
	else if(strstr(filePath,".txt") == NULL)
	{
		printf("listfile_FAILURE %s\n", ERR_VFS_LISTFILE_02);
		return;
	}
	else
	{
		fd *searchedFile = bstSearchNode(&bstRoot, filePath);
		//printf("searched file in BST= %s",searchedFile->file_name);
	
		if(searchedFile == NULL)
		{
			printf("listfile_FAILURE %s\n", ERR_VFS_LISTFILE_01);
			return;
		}
		else
		{
			/*fclose(fp);
			fp = fopen(outputfile, "w");*/
		
			blockNumr = searchedFile->blockNum;
			//printf("\nBlock number=%d\n",blockNumr);
			FILE *fptr=fopen(header.fileSystemLabel,"rb");

			if(fptr==NULL)
			{
				printf("listfile_FAILURE %s\n", ERR_VFS_MOUNT_02);
				return;
			}
			else
			{	
				while(ch!='!')
				{
					fread(&ch,sizeof(ch),1,fptr);
					
					file_offset1++;
				}
				//printf("\nfile_offset1 listfile=%d\n",file_offset1);
				//printf("\nblock number in listfile=%d\n",blockNumr);
				fseek(fptr,(file_offset1+(blockNumr*1024)),SEEK_SET);
			
				while((readChars = fgetc(fptr)) != EOF)
				{	//printf("%c",readChars);
					fputc(readChars, fp);
					
					
				}
				/*int s=0;
				while(s<(searchedFile->fileSize))
				{
					readChars = fgetc(fptr);
					printf("%c",readChars);
					fputc(readChars, fp);
					s++;
				}*/

			
			
			}
		fclose(fptr);

		}
	}

	printf("listfile_SUCCESS\n");
}
